package com.shao.im.service.impl;

import com.shao.im.entity.Email;
import com.shao.im.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Async
    @Override
    public void sendEmail(Email email) {
        log.debug("[send Email] 发送邮件 - {}", email);
        // 发送邮件的核心代码
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 邮箱设置的辅助对象(spring封装的) - 装饰者模式
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            // 设置标题
            mimeMessageHelper.setSubject(email.getSubject());
            // 设置发送方
            mimeMessageHelper.setFrom(from);
            // 设置接收方
            mimeMessageHelper.setTo(email.getTo());
            // 设置内容
            mimeMessageHelper.setText(email.getContent());

            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
